define(['butterfly/view', 'jquery', 'butterfly/listview/DataSource', 'butterfly/listview/ListView',
		'butterfly/notification', 'iscroll'],
	function(View, $, DataSource, ListView, Notification, IScroll) {
		return View.extend({
			id: 'mail_detail',
			myScroll: null,
			textMyScroll: null,
			events: {
				"click a[data-action='back']": "goback",
				"click .baseExtend": "baseExtend",
				"click .reply": "reply",
				"click .replyAll": "replyAll",
				"click .forwarding": "forwarding"
				
			},
			initialize: function(){
				console.log("gogogo");
				var me = this;
				var mailID=this.getUrlVar("mailID");
				console.info(mailID);
			},
			render: function() {
				var me = this;
				var cache = null;
				me.hideWasteBox();
				var mailID=me.getUrlVar("mailID");
				var mailType=me.getUrlVar("mailType");
	
				// console.log(me.Session.loadObject(mailID));
				var sessionDataSource = me.Session.loadObject(mailID);
				if (sessionDataSource != null) {
					me.detailDataSource(sessionDataSource);
					console.info('dataSource is session');
				}
				else {
					console.log(mailID);
					var mailDetail=me.loadData(mailID);
					console.info('dataSource is updata');
					me.Session.saveObject(mailID, mailDetail);
					me.Session.loadObject(mailID);
					me.detailDataSource(mailDetail);
				}
			
			},
				loadData:function(mailId){
    			var me=this;
    			var mailType=me.getUrlVar("mailType");
    	
    			var localstorage = window.localStorage[mailType+"_detail"];
    			me.cache=JSON.parse(localstorage);
    			console.log(me.cache);
    			var jsonobj=_.find(me.cache,function(obj){
    				 if(obj.id==mailId)
    				 return obj;
    			});
    			console.log(jsonobj);
    			return jsonobj;
    		},
				detailDataSource: function(data) {
				var me = this;
				console.log(data);
				if(data!=''){
					data.body = data.body.replace(/<base/, "<a");
					//add by lcg(本版本暂时不支持a标签打开)
					data.body = data.body.replace(/href\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^"\'>\s]+))/g,"href='#/changan/notavailabe'");
					// data.data.body = data.data.body.replace('target="_blank"',"");
					data.body = data.body.replace(/target=[\'"]_blank[\'"]/,"");
					// me.$('.title').html('');
					me.$('.title').html(data.subject); //标题
					// me.$('.mailContent').html('');
					me.$('.mailContent').html(data.body); //正文
					// me.$('.baseName').html('');
					me.$('.baseName').html(data.fromusername); //发件人
					if (typeof date != 'undefined' && date != '') {
						me.$el.find('.baseDate').html(data.substring(0, 16)); //日期
					}
					var toaddress = data.toaddress;
					if (toaddress.indexOf('-') > -1 && toaddress.indexOf('<') > -1) {
						toaddress = toaddress.split(',');
						var newAddress = [];
						_.each(toaddress, function(value) {
							var name = value.substring(0, value.indexOf('-'));
							var address = value.substring(value.indexOf('<'), value.length);
							var newArr = name + address;
							newAddress.push(newArr);
						})
						data.toaddress = newAddress.toString();
					}
					me.Session.saveObject("detail-cc", data.cc); //抄送人截取部门信息传递到写邮件页面。
					me.Session.saveObject("detail-fromaddress", data.fromaddress);
					me.Session.saveObject("detail-subject", data.subject);
					me.Session.saveObject("detail-body", data.body);
					me.Session.saveObject("detail-attachement", data.attachement);
				
					//收件人
					var address = data.toaddress.split(",");
					me.$('.addressInfo').html('');	
					for (var i = 0; i < address.length; i++) {
						var addressText = me.$el.find('.addressInfo').text();
						me.$el.find('.addressInfo').text(addressText + address[i].substring(0, address[i].indexOf("<")) + ",")
					}
					//抄送人
					var makeCopy = "";
					if (data.cc != "") {
						makeCopy = data.cc.split(",");
					} else {
						me.$el.find('.sender').hide();
					}
					for (var i = 0; i < makeCopy.length; i++) {
						var ccText = me.$el.find('.makeCopyInfo').text();
						me.$el.find('.makeCopyInfo').text(ccText + makeCopy[i].substring(0, makeCopy[i].indexOf("<")) + ",")
					}
					//附件

					if (data.attachement.length > 0) {
						console.log(data.attachement);
						_.each(data.attachement,function(item) {
							var template = _.template($("#attachement-template").html(),item);
							me.$el.find('.attche-download').append(template);
						});
					}
				}
				else {
					Notification.show({
						type: "error",
						message: '获取数据失败',
					});
				}
			
			},

			 	Session :{
			 	// var Session={saveObject,loadObject,deleteObject};
				saveObject : function(key, object) {
				window.sessionStorage[key] = JSON.stringify(object);
				},

				loadObject : function(key) {
				var objectString =  window.sessionStorage[key];
				return objectString == null ? null : JSON.parse(objectString);
				},

				deleteObject : function(key) {
				window.sionStorage[key] = null;
				},
			
			},
			 	getUrlVars : function(){
				var vars = [], hash;
				var href = window.location.href;
				 var hashes = href.slice(href.indexOf('?') + 1).split('&');
				for(var i = 0; i < hashes.length; i++)
    			{
      			hash = hashes[i].split('=');
     			 vars.push(hash[0]);
     			 vars[hash[0]] = hash[1];
  			  	}
    			return vars;
				},

			 	getUrlVar : function(name){
				return this.getUrlVars()[name];
				},
				hideWasteBox: function() {
				var me = this;
				if (this.getUrlVar('mailType') === 'wasteBox') {
					me.$el.find('.move').hide();
				}
			},
				baseExtend: function() {
				var me = this;
				var tag = $('.allExtend').css("white-space");

				if (tag === "nowrap") {
					$('.allExtend').css({
						"white-space": "normal",
						'height':'auto'
					});
					me.myScroll.refresh();
				} else {
					$('.allExtend').css({
						"white-space": "nowrap",
						'height':'16px'
					});
					me.myScroll.refresh();

				}
				},
				reply: function() {
				Backbone.history.navigate('/mail/sendMail.html', {
					trigger: true
				});
			},
				replyAll: function() {
				Backbone.history.navigate('/mail/sendMail.html', {
					trigger: true
				});
			},
				forwarding: function() {
				Backbone.history.navigate('/mail/sendMail.html?', {
					trigger: true
				});
			},
			
				goback:function(){
				window.history.back();
			}
			}); //view define

		});
